#!/usr/bin/env python3
"""
量表状态管理工具
用于更新量表的发布状态和公开设置
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from app import create_app, db
from app.models import Scale
from sqlalchemy import text

def list_scales():
    """列出所有量表及其状态"""
    app = create_app()
    
    with app.app_context():
        print("=== 量表列表 ===")
        
        scales = Scale.query.order_by(Scale.id).all()
        
        print(f"{'ID':<4} {'标题':<30} {'状态':<12} {'公开':<6} {'题目数':<8}")
        print("-" * 70)
        
        for scale in scales:
            print(f"{scale.id:<4} {scale.title[:28]:<30} {scale.status:<12} {'是' if scale.is_public else '否':<6} {scale.question_count or 0:<8}")

def update_scale_status(scale_id, status=None, is_public=None):
    """更新量表状态"""
    app = create_app()
    
    with app.app_context():
        scale = Scale.query.get(scale_id)
        
        if not scale:
            print(f"❌ 量表 {scale_id} 不存在")
            return
        
        print(f"📋 当前量表信息:")
        print(f"   ID: {scale.id}")
        print(f"   标题: {scale.title}")
        print(f"   状态: {scale.status}")
        print(f"   公开: {'是' if scale.is_public else '否'}")
        print()
        
        updated = False
        
        if status and status != scale.status:
            old_status = scale.status
            scale.status = status
            print(f"✅ 状态已更新: {old_status} → {status}")
            updated = True
        
        if is_public is not None and is_public != scale.is_public:
            old_public = scale.is_public
            scale.is_public = is_public
            print(f"✅ 公开设置已更新: {'是' if old_public else '否'} → {'是' if is_public else '否'}")
            updated = True
        
        if updated:
            # 如果发布量表，自动设置发布时间
            if status == 'PUBLISHED' and not scale.published_at:
                from datetime import datetime
                scale.published_at = datetime.now()
                print(f"✅ 发布时间已设置: {scale.published_at}")
            
            db.session.commit()
            print(f"🎉 量表 {scale_id} 更新成功！")
        else:
            print("ℹ️  没有需要更新的内容")

def publish_scale(scale_id):
    """发布量表（设为PUBLISHED和公开）"""
    update_scale_status(scale_id, status='PUBLISHED', is_public=True)

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("量表状态管理工具")
        print("用法:")
        print("  python manage_scales.py list                    # 列出所有量表")
        print("  python manage_scales.py publish <scale_id>      # 发布量表（设为已发布且公开）")
        print("  python manage_scales.py status <scale_id> <status>  # 更新状态（DRAFT/PUBLISHED/ARCHIVED）")
        print("  python manage_scales.py public <scale_id> <0|1>     # 设置公开状态（0=不公开，1=公开）")
        print()
        print("示例:")
        print("  python manage_scales.py publish 7               # 发布量表7")
        print("  python manage_scales.py status 7 PUBLISHED      # 将量表7设为已发布")
        print("  python manage_scales.py public 7 1              # 将量表7设为公开")
        sys.exit(1)
    
    command = sys.argv[1]
    
    if command == "list":
        list_scales()
    elif command == "publish" and len(sys.argv) >= 3:
        scale_id = int(sys.argv[2])
        publish_scale(scale_id)
    elif command == "status" and len(sys.argv) >= 4:
        scale_id = int(sys.argv[2])
        status = sys.argv[3].upper()
        if status not in ['DRAFT', 'PUBLISHED', 'ARCHIVED']:
            print("❌ 状态必须是 DRAFT、PUBLISHED 或 ARCHIVED")
            sys.exit(1)
        update_scale_status(scale_id, status=status)
    elif command == "public" and len(sys.argv) >= 4:
        scale_id = int(sys.argv[2])
        is_public = bool(int(sys.argv[3]))
        update_scale_status(scale_id, is_public=is_public)
    else:
        print("❌ 无效的命令或参数")
        sys.exit(1)